package com.ftg.learn.util;

import com.ftg.learn.system.entity.Log;
import com.ftg.learn.system.service.ILogService;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

/**
 * 日志前置守卫
 * <p>
 * 用于处理springboot controller的前置赛守卫,
 * 此守卫用来处理日志功能。
 *
 * @author kangjx
 * @version 1.0
 * @date 2023/4/26 上午9:40
 */
public class LogsControllerGuard implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(LogsControllerGuard.class);

    /**
     * 处理日志实体类相关信息
     *
     * @param request 请求
     * @return log 日志
     */
    private Log initLog(HttpServletRequest request) {
        //req就是request请求
        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        //获取浏览器信息
        Browser browser = userAgent.getBrowser();
        //获取操作系统信息
        OperatingSystem os = userAgent.getOperatingSystem();

        Log log = new Log();
        log.setLogIp(request.getRemoteAddr());
        log.setLogBrowser(browser.getName());
        log.setLogMethod(request.getMethod());
        //模块名称转中文
        String url = request.getRequestURI();
        String moudleName = url.substring(url.indexOf("/api/") + 5, url.indexOf("/", url.indexOf("/api/") + 5));
        log.setLogModule(MoudleNameEnum.valueOf(moudleName).getZh_name());

        log.setLogApi(url);

        log.setLogSystem(os.toString());

        log.setLogOperator(LocalDateTime.now());
        log.setGmtCreate(LocalDateTime.now());

        return log;
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //获得日志处理类
        ILogService iLogService = SpringApplicationContext.getBean(ILogService.class);
        logger.info("拦截器开始");
        //日志添加功能
        iLogService.save(initLog(request));

        //默认登陆地址
        String loginUrl = "/api/system/user/login";
        String captchaUrl = "/api/system/user/captcha";

        if (!request.getRequestURI().equals(loginUrl) && !request.getRequestURI().equals(captchaUrl)) {
            String token = request.getHeader("token");
            System.out.println(token);
            //token出现错误以后，直接方法抛出异常，然后让全局异常直接处理掉了
            JwtUtil.verifyJwtToken(token);
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
    }
}
